package com.lkd.handler;

import com.lkd.business.MsgHandler;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.emq.Topic;
import com.lkd.entity.ChannelEntity;
import com.lkd.exception.LogicException;
import com.lkd.service.ChannelService;
import com.lkd.utils.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Component
@Topic(TopicConfig.VMS_SUPPLY_TOPIC)
public class SupplyMsgHandler implements MsgHandler {

    @Autowired
    private ChannelService channelService;

    @Override
    public void process(String jsonMsg) throws IOException {
        SupplyContract supplyContract = JsonUtil.getByJson(jsonMsg, SupplyContract.class);
        if (supplyContract == null) {
            throw new LogicException("完成补货工单参数为空");
        }
        //根据设备编号查询货道列表
        List<ChannelEntity> channeles = channelService.getChannelesByInnerCode(supplyContract.getInnerCode());
        //遍历补货数据,根据货道ID匹配对应设备货道
        List<SupplyChannel> supplyDatas = supplyContract.getSupplyData();
        for (SupplyChannel supplyChannel : supplyDatas) {

            //两种遍历匹配方法,stream流效率更高
//            ChannelEntity channelEntity = new ChannelEntity();
//            for (ChannelEntity channel : channeles) {
//                if (channel.getChannelCode().equals(supplyChannel.getChannelId())){
//                    channelEntity=channel;
//                }
//            }
            Optional<ChannelEntity> item = channeles.stream()
                    .filter(channel -> channel.getChannelCode().equals(supplyChannel.getChannelId()))
                    .findFirst();
            ChannelEntity channelEntity = item.get();

            if (item.isPresent()) {
                int capacity = channelEntity.getCurrentCapacity() + supplyChannel.getCapacity();
                if (capacity > channelEntity.getMaxCapacity()) {
                    throw new LogicException("补货数量超出最大货物容量");
                }
                channelEntity.setCurrentCapacity(capacity);
                channelEntity.setLastSupplyTime(LocalDateTime.now());
                channelService.updateById(channelEntity);
            }
        }
    }
}
